package cn.thr.ymcc.web.controller;

import cn.thr.ymcc.constant.Cos;
import cn.thr.ymcc.dto.KillDto;
import cn.thr.ymcc.jwt.LoginContextUtils;
import cn.thr.ymcc.query.KillCourseQuery;
import cn.thr.ymcc.result.JsonResult;
import cn.thr.ymcc.result.PageList;
import cn.thr.ymcc.service.IKillCourseService;
import cn.thr.ymcc.domain.KillCourse;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/killCourse")
public class KillCourseController {

    @Autowired
    public IKillCourseService killCourseService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private LoginContextUtils loginContextUtils;

    /**
     * 用户点击“立即抢购” 执行秒杀业务
     * @param killDto
     * @return
     */
    @PostMapping("/kill")
    public JsonResult kill(@RequestBody KillDto killDto, HttpServletRequest request){
        //获取当前登录用户id
        Long loginUserId = loginContextUtils.getLoginUserId(request.getHeader(LoginContextUtils.JWT_TOKEN_NAME));
        killDto.setLoginId(loginUserId);
        return JsonResult.me(killCourseService.kill(killDto));
    }

    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody KillCourse killCourse){
        if(killCourse.getId()!=null){
            killCourseService.updateById(killCourse);
        }else{
            killCourseService.save(killCourse);
        }
        return JsonResult.me();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        killCourseService.removeById(id);
        return JsonResult.me();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")String id){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(Cos.Kill.KEY_KILL_COURSE);
        return JsonResult.me().setData(hashOps.get(id));
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(Cos.Kill.KEY_KILL_COURSE);

        return JsonResult.me().setData(hashOps.values());
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody KillCourseQuery query){
        Page<KillCourse> page = new Page<KillCourse>(query.getPageNo(), query.getPageSize());
        page = killCourseService.page(page);
        return JsonResult.me().setData(new PageList<KillCourse>(page.getTotal(), page.getRecords()));
    }
}
